<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <!-- 搜索表单 -->
        <div>
          <el-form
            ref="queryForm"
            :model="queryParams"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="房号" prop="infoId">
              <el-input
                id="infoId"
                v-model="queryParams.infoId"
                placeholder="请输入房间号"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="房型" prop="infoName">
              <el-select
                id="infoName"
                v-model="queryParams.infoName"
                clearable
                placeholder="请选择"
                @keyup.enter.native="handleQuery"
              >
                <el-option
                  v-for="item in roomTypeOptions"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="入住时间" prop="inTime">
              <el-date-picker
                v-model="queryParams.inTime"
                type="date"
                value-format="yyyy-MM-ddTHH:mm:ss.SSSZ"
                placeholder="选择日期"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item label="退房时间" prop="outTime">
              <el-date-picker
                v-model="queryParams.outTime"
                type="date"
                value-format="yyyy-MM-ddTHH:mm:ss.SSSZ"
                placeholder="选择日期"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="联系方式" prop="cusPhoneNum">
              <el-input
                id="cusPhoneNum"
                v-model="queryParams.cusPhoneNum"
                placeholder="请输入顾客联系方式"
                clearable
                size="small"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- 按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <div>
          <!-- 数据操作按钮 -->
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button
                v-hasAuthority="['pos:order:pay']"
                type="success"
                size="small"
                icon="el-icon-edit"
                :disabled="payDepositButton"
                @click="showDepositPayment"
                >支付押金</el-button
              >
              <el-button
                v-hasAuthority="['pos:order:pay']"
                type="primary"
                size="small"
                icon="el-icon-money"
                :disabled="payButton"
                @click="showPaymentForm"
                >支付房费</el-button
              >
              <el-button
                type="info"
                size="small"
                icon="el-icon-check"
                :disabled="outRoomButton"
                @click="handleCheckOut"
                >退房</el-button
              >
              <el-button
                type="warning"
                size="small"
                icon="el-icon-star-off"
                :disabled="multiple"
                @click="handleGenerate"
                >导出</el-button
              >
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                :disabled="cancelButton"
                @click="handleAllCancel"
                >取消</el-button
              >
            </el-col>
          </el-row>

          <!-- 数据展示list -->
          <el-table
            :data="tableData.list"
            style="width: 100%; margin-bottom: 20px"
            row-key="orderId"
            border
            default-expand-all
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="orderId" label="订单号" width="80px" />
            <el-table-column prop="infoId" label="房号" width="80px" />
            <el-table-column prop="typeId" label="房型号" width="80px" />
            <el-table-column prop="infoName" label="房型" width="110" />
            <el-table-column prop="orderPrice" label="价格" width="90px" />
            <el-table-column prop="cusName" label="顾客姓名" width="90" />
            <!-- <el-table-column prop="cusId" label="顾客身份证" width="170" /> -->
            <el-table-column
              prop="cusPhoneNum"
              label="顾客联系方式"
              width="110px"
            />
            <el-table-column prop="inTime" label="入住时间" />
            <el-table-column prop="outTime" label="退房时间" />
            <el-table-column prop="roomOrderId" label="标识号" width="80px" />
            <el-table-column prop="orderStatus" label="订单状态" />
            <el-table-column prop="roomStatus" label="房间状态" />
            <!-- <el-table-column
              prop="orderStatus"
              label="状态"
              width="100"
              :filters="[{ text: '家', value: '家' }, { text: '公司', value: '公司' }]"
              :filter-method="filterTag"
              filter-placement="bottom-end"
            >
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.tag === '家' ? 'primary' : 'success'"
                  disable-transitions
                >{{ scope.row.tag }}</el-tag>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center" width="150px">
              <template slot-scope="scope">
                <el-button
                  v-hasAuthority="['pos:order:checkIn']"
                  size="small"
                  type="text"
                  icon="el-icon-edit"
                  :disabled="scope.row.payButtonL"
                  @click="handleCheckIn(scope.row)"
                  >入住</el-button
                >
                <el-button
                  v-hasAuthority="['pos:order:edit']"
                  size="small"
                  type="text"
                  icon="el-icon-edit"
                  :disabled="updateButtonL"
                  @click="handleUpdate(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="small"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleCheckOut(scope.row)"
                  >退房</el-button
                >
                <el-button
                  v-hasAuthority="['pos:order:cancel']"
                  size="small"
                  type="text"
                  icon="el-icon-edit"
                  :disabled="cancelButtonL"
                  @click="handleCancel(scope.row)"
                  >取消</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div>
          <!-- 修改订单信息表单 -->
          <el-dialog
            title="信息修改"
            :visible.sync="dialogFlag"
            width="500px"
            append-to-body
            :close-on-click-modal="false"
          >
            <el-form
              ref="form"
              :model="form"
              label-width="110px"
              :rules="rules"
            >
              <el-form-item label="标识号" prop="roomOrderId">
                <el-input
                  v-model="form.roomOrderId"
                  placeholder="请输入标识"
                  :disabled="true"
                />
              </el-form-item>
              <el-form-item label="订单号" prop="orderId">
                <el-input
                  v-model="form.orderId"
                  placeholder="请输入订单号"
                  :disabled="true"
                />
              </el-form-item>
              <el-form-item label="房号" prop="infoId">
                <!-- <el-input v-model="form.infoId" placeholder="请输入房号" /> -->
                <el-select
                  id="infoId"
                  v-model="form.infoId"
                  placeholder="请分配入住房间"
                  :disabled="judgeInfoId"
                  @keyup.enter.native="submitForm"
                >
                  <el-option
                    v-for="item in roomIdOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="房型" prop="infoName">
                <el-select
                  id="infoName"
                  v-model="form.infoName"
                  clearable
                  placeholder="请选择"
                  @change="updateInput"
                  @keyup.enter.native="submitForm"
                >
                  <el-option
                    v-for="item in roomTypeOptions"
                    :key="item.typeId"
                    :label="item.typeName"
                    :value="item.typeName"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="房型号" prop="typeId">
                <el-input
                  v-model="form.typeId"
                  placeholder="请输入房型号"
                  :disabled="true"
                  @keyup.enter.native="submitForm"
                />
              </el-form-item>
              <el-form-item label="价格" prop="orderPrice">
                <el-input
                  v-model="form.orderPrice"
                  placeholder="请输入价格"
                  :disabled="true"
                  @keyup.enter.native="submitForm"
                />
              </el-form-item>
              <el-form-item label="顾客姓名" prop="cusName">
                <el-input
                  v-model="form.cusName"
                  placeholder="请输入顾客姓名"
                  @keyup.enter.native="submitForm"
                />
              </el-form-item>
              <el-form-item
                label="顾客身份证号"
                prop="cusId"
                label-width="110px"
                @keyup.enter.native="submitForm"
              >
                <el-input
                  v-model="form.cusId"
                  placeholder="请输入顾客身份证号"
                  @keyup.enter.native="submitForm"
                />
              </el-form-item>
              <el-form-item label="顾客联系方式" prop="cusPhoneNum">
                <el-input
                  v-model="form.cusPhoneNum"
                  placeholder="请输入顾客联系方式"
                  @keyup.enter.native="submitForm"
                />
              </el-form-item>
              <el-form-item label="入住时间" prop="inTime">
                <el-date-picker
                  v-model="form.inTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :picker-options="inTimeOptions"
                />
              </el-form-item>
              <el-form-item label="退房时间" prop="outTime">
                <el-date-picker
                  v-model="form.outTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :picker-options="outTimeOptions"
                />
              </el-form-item>
              <!-- <el-form-item label="状态" prop="orderStatus">
                <el-select
                  id="infoStatus"
                  v-model="form.orderStatus"
                  clearable
                  placeholder="请选择"
                  :disabled="statusSel"
                >
                  <el-option label="未支付" value="未支付" />
                  <el-option label="已支付" value="已支付" />
                  <el-option label="已取消" value="已取消" />
                  <el-option label="已退房" value="已退房" />
                </el-select>
              </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 生成框 -->
        <el-dialog
          title="入住单"
          :visible.sync="dialogFlag2"
          width="700px"
          append-to-body
          :close-on-click-modal="false"
        >
          <el-descriptions
            v-for="(group, index) in idsRow"
            :key="index"
            :column="3"
            border
            class="margin-top"
            :title="'订单' + (index + 1)"
          >
            <el-descriptions-item label="订单号" prop="orderId">
              {{ group.orderId }}
            </el-descriptions-item>
            <el-descriptions-item label="房号" prop="infoId">
              {{ group.infoId }}
            </el-descriptions-item>
            <el-descriptions-item label="房型" prop="infoName">
              {{ group.infoName }}
            </el-descriptions-item>
            <el-descriptions-item label="入住人姓名" prop="cusName">
              {{ group.cusName }}
            </el-descriptions-item>
            <el-descriptions-item label="入住人身份证" prop="cusId">
              {{ group.cusId }}
            </el-descriptions-item>
            <el-descriptions-item label="入住人联系方式" prop="cusPhoneNum">
              {{ group.cusPhoneNum }}
            </el-descriptions-item>
            <el-descriptions-item label="标识号" prop="roomOrderId">
              {{ group.roomOrderId }}
            </el-descriptions-item>
            <el-descriptions-item label="入住时间" prop="inTime">
              {{ group.inTime }}
            </el-descriptions-item>
            <el-descriptions-item label="退房时间" prop="outTime">
              {{ group.outTime }}
            </el-descriptions-item>
            <el-descriptions-item label="订单状态" prop="orderStatus">
              <el-tag size="small">{{ group.orderStatus }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="房间状态" prop="roomStatus">
              <el-tag size="small">{{ group.roomStatus }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
          <div slot="footer" class="dialog-footer">
            <el-button @click="DesCancel">确定</el-button>
          </div>
        </el-dialog>

        <!--押金支付方式选择  -->
        <div>
          <el-dialog
            title="选择支付方式"
            :visible.sync="dialogFlagDeposit"
            width="700px"
            append-to-body
            :close-on-click-modal="false"
          >
            <el-form
              ref="depositPaymentWayForm"
              :model="depositPaymentWayForm"
              :inline="true"
              label-width="80px"
            >
              <el-form-item label="支付方式">
                <el-radio-group v-model="depositPaymentWayForm.way">
                  <el-radio label="现金支付" />
                  <el-radio label="支付宝支付" />
                </el-radio-group>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="onDepositSubmit"
                >确定</el-button
              >
              <el-button @click="paywayCancel">取消</el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 押金支付现金支付页面 -->
        <div>
          <el-dialog
            :visible.sync="dialogFlagDPBCash"
            width="700px"
            append-to-body
            :close-on-click-modal="false"
          >
            <el-form
              ref="depositCashNumForm"
              :model="depositCashNumForm"
              :inline="true"
              label-width="80px"
            >
              <el-form-item label="实付金额">
                <el-input
                  v-model="depositCashNumForm.actuallyPay"
                  placeholder="请输入客户实付金额"
                  @keyup.enter.native="depositCashSubmit"
                />
              </el-form-item>
              <el-form-item label="应付金额">
                <el-input
                  v-model="depositCashNumForm.shouldPay"
                  placeholder="请输入客户应付金额"
                  :disabled="shouldPayInput"
                />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="depositCashSubmit"
                >确定</el-button
              >
              <el-button @click="depositCashCancel">取消</el-button>
            </div>
          </el-dialog>
        </div>

        <div>
          <!--房费支付方式选择表单 -->
          <el-dialog
            title="选择支付方式"
            :visible.sync="dialogFlag3"
            width="700px"
            append-to-body
            :close-on-click-modal="false"
          >
            <el-form
              ref="paymentWayForm"
              :model="paymentWayForm"
              :inline="true"
              label-width="80px"
            >
              <el-form-item label="支付方式">
                <el-radio-group v-model="paymentWayForm.way">
                  <el-radio label="现金支付" />
                  <el-radio label="支付宝支付" />
                </el-radio-group>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="onSubmit">确定</el-button>
              <el-button @click="paywayCancel">取消</el-button>
            </div>
          </el-dialog>
        </div>

        <div>
          <!-- 判断金额是否对等表格 -->
          <el-dialog
            :visible.sync="dialogFlag4"
            width="700px"
            append-to-body
            :close-on-click-modal="false"
          >
            <el-form
              ref="cashNumForm"
              :model="cashNumForm"
              :inline="true"
              label-width="80px"
            >
              <el-form-item label="实付金额">
                <el-input
                  v-model="cashNumForm.actuallyPay"
                  placeholder="请输入客户实付金额"
                  @keyup.enter.native="cashSubmit"
                />
              </el-form-item>
              <el-form-item label="应付金额">
                <el-input
                  v-model="cashNumForm.shouldPay"
                  placeholder="请输入客户应付金额"
                  :disabled="shouldPayInput"
                />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="cashSubmit">确定</el-button>
              <el-button @click="cashCancel">取消</el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 预定订单入住页面 -->
        <div>
          <el-dialog
            ref=""
            title="办理入住"
            :visible.sync="dialogFlagCkeckIn"
            width="400px"
            :model="formTwo"
            append-to-body
            :close-on-click-modal="false"
          >
            <el-form>
              <el-form-item label="房型号">
                <el-input
                  v-model="formTwo.typeId"
                  placeholder="请输入房型号"
                  style="width: 100px"
                  :disabled="true"
                />
              </el-form-item>
              <el-form-item label="房间号">
                <el-select
                  id="infoId"
                  v-model="formTwo.infoId"
                  placeholder="请分配入住房间"
                  @keyup.enter.native="submitCheckIn"
                >
                  <el-option
                    v-for="item in roomIdOptions"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitCheckIn">提交</el-button>
            </div>
          </el-dialog>
        </div>
        <div>
          <!-- 分页加载 -->
          <el-pagination
            :current-page="queryParams.pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="queryParams.pageSize"
            layout="total,sizes,prev,pager,next,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getRoomInfo, listAllRoomInfo } from "@/api/pos/roomInfo";
import { listAllRoomType } from "@/api/pos/roomType";
import {
  listOrderByPage,
  updateOrderInfo,
  getOrderInfo,
  cancelOrder,
  cancelRoom,
  getAlipay,
  roomCheckOut,
  cashPay,
  checkInRoom,
  checkInRoomId,
  payDepositByCash,
  judgePayDeposit,
  calculateDeposit,
} from "@/api/pos/roomSale";
import { listroomOrderByPage } from "@/api/pos/roomOrder";
import moment from "moment";
import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
export default {
  name: "RoomSale",
  mounted() {
    this.getList();
  },
  data() {
    return {
      // 设置时间限制
      inTimeOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      // 房费支付方式
      paymentWayForm: {
        way: "",
      },
      // 押金支付方式
      depositPaymentWayForm: {
        way: "",
      },
      cashPayMultiple: [],
      cashPayArray: {
        orderId: "",
        payPrice: "",
        orderStatus: null,
      },
      totalPay: 0,
      // 现金支付判断
      cashNumForm: {
        actuallyPay: "",
        shouldPay: 0,
        orderStatus: "",
        roomStatus: "",
      },
      // 押金现金支付判断
      depositCashNumForm: {
        actuallyPay: "",
        shouldPay: 0,
        orderStatus: "",
      },
      dialogFlag: false,
      dialogFlag2: false,
      dialogFlag3: false,
      dialogFlag4: false,
      dialogFlagCkeckIn: false,
      dialogFlagDeposit: false,
      dialogFlagDPBCash: false,
      tableData: [],
      roomTypeOptions: [],
      roomIdOptions: [],
      // 按钮
      single: true,
      payButton: true,
      outRoomButton: true,
      updateButton: true,
      cancelButton: true,
      payDepositButton: true,
      // list的按钮
      payButtonL: false,
      updateButtonL: false,
      cancelButtonL: false,
      ids: [],
      idsRow: [],
      statusSel: false,
      shouldPayInput: true,
      // 勾选1个或多个
      multiple: true,
      // 修改表单房号框的控制
      judgeInfoId: false,
      // 修改订单
      form: {
        roomOrderId: null,
        orderId: null,
        infoId: null,
        infoName: null,
        typeId: null,
        typeName: null,
        orderPrice: null,
        cusName: null,
        cusId: null,
        cusPhoneNum: null,
        orderStatus: null,
        roomStatus: null,
        inTime: null,
        outTime: null,
      },
      formTwo: {
        typeId: null,
        infoId: null,
        orderId: null,
        roomOrderId: null,
      },
      descriptions: {
        roomOrderId: null,
        orderId: null,
        infoId: null,
        infoName: null,
        type: null,
        typeName: null,
        orderPrice: null,
        cusName: null,
        cusId: null,
        cusPhoneNum: null,
        orderStatus: null,
        roomStatus: null,
        inTime: null,
        outTime: null,
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomOrderId: null,
        orderId: null,
        infoId: null,
        infoName: null,
        typeName: null,
        type: null,
        orderPrice: null,
        cusName: null,
        // cusId: null,
        cusPhoneNum: null,
        orderStatus: null,
        roomStatus: null,
        inTime: null,
        outTime: null,
      },
      rules: {
        orderId: [
          { required: true, message: "订单号不能为空", trigger: "blur" },
        ],
        infoId: [{ required: true, message: "房号不能为空", trigger: "blur" }],
        typeId: [
          { required: true, message: "房型号不能为空", trigger: "blur" },
        ],
        infoName: [
          { required: true, message: "房型不能为空", trigger: "blur" },
        ],
        orderPrice: [
          { required: true, message: "价格不能为空", trigger: "blur" },
        ],
        cusName: [
          { required: true, message: "顾客名不能为空", trigger: "blur" },
        ],
        cusId: [{ required: true, message: "身份证不能为空", trigger: "blur" }],
        cusPhoneNum: [
          { required: true, message: "联系方式不能为空", trigger: "blur" },
        ],
        inTime: [
          { required: true, message: "入住时间不能为空", trigger: "blur" },
        ],
        outTime: [
          { required: true, message: "退房时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  // 计算属性，可选
  computed: {
    // 设置退房时间
    outTimeOptions() {
      return {
        disabledDate: this.outTimeDisabledDate,
      };
    },
  },

  // 监控data变化，可选
  watch: {},

  // 生命周期-创建完成，可选
  created() {
    // 生命周期-挂载完成，可选
    this.getroomTypeOptions();
    // this.getroomIdOptions()
    this.getList();
  },
  methods: {
    // 获取数据
    async getList() {
      const data = await listOrderByPage(this.queryParams);
      data.data.list = this.changeList(
        data.data.list.map((item) => {
          // item.roomOrderIds = item.roomOrderId
          item.orderId = item.orderInfo.orderId;
          item.infoId = item.roomStatus.infoId;
          item.typeId = item.roomStatus.typeId;
          item.infoName = item.roomType.typeName;
          item.orderPrice = item.orderInfo.orderPrice;
          item.cusName = item.customer.cusName;
          item.cusId = item.customer.cusId;
          item.cusPhoneNum = item.customer.cusPhoneNum;
          const intTimeOne = moment(item.roomStatus.inTime);
          item.inTime = intTimeOne.format("YYYY-MM-DD");
          const outTimeOne = moment(item.roomStatus.outTime);
          item.outTime = outTimeOne.format("YYYY-MM-DD");
          item.orderStatus = item.orderInfo.orderStatus;
          item.roomStatus = item.roomStatus.roomStatus;
          // item.orderStatus = item.roomOrder.orderStatus
          item.children = [];
          if (item.inTime) {
            item.inTime = item.inTime.slice(0, 10);
          }
          if (item.outTime) {
            item.outTime = item.outTime.slice(0, 10);
          }
          // 设置payButtonL属性
          item.payButtonL = item.infoId !== 0;

          return item;
        })
      );
      this.tableData = data.data;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderId);
      this.idsRow = selection.map((item) => {
        return {
          roomOrderId: item.roomOrderId,
          orderId: item.orderId,
          infoId: item.infoId,
          infoName: item.infoName,
          orderPrice: item.orderPrice,
          cusName: item.cusName,
          cusId: item.cusId,
          cusPhoneNum: item.cusPhoneNum,
          inTime: item.inTime,
          outTime: item.outTime,
          orderStatus: item.orderStatus,
          roomStatus: item.roomStatus,
        };
      });
      // console.log('选中行的所有数据：', this.idsRow[0])
      this.multiple = !selection.length;
      this.payButton = !selection.length;
      this.payDepositButton = !selection.length;
      this.outRoomButton = true;
      this.cancelButton = selection.length !== 1;
      for (let i = 0; i <= selection.length - 1; i++) {
        if (
          this.idsRow[i].roomStatus === "可入住" &&
          this.idsRow[i].orderStatus === "已支付"
        ) {
          this.outRoomButton = true;
          this.payButton = true;
          this.cancelButton = true;
          this.payDepositButton = true;
        } else if (this.idsRow[i].orderStatus === "已支付") {
          this.payButton = true;
          this.cancelButton = true;
          this.payDepositButton = true;
          // this.outRoomButton = false
          this.outRoomButton = selection.length !== 1;
        } else if (this.idsRow[i].orderStatus === "已取消") {
          this.cancelButton = true;
          this.payButton = true;
          // this.outRoomButton = true
          this.updateButton = true;
          this.payDepositButton = true;
        } else if (this.idsRow[i].orderStatus === "已退房") {
          this.cancelButton = true;
          this.payButton = true;
          // this.outRoomButton = true
          this.updateButton = true;
          this.payDepositButton = true;
        }
      }
    },

    // 树型数据
    changeList(originalArray) {
      const newArray = [];
      const idMap = {};
      originalArray.forEach((obj) => {
        if (!idMap[obj.orderId]) {
          newArray.push({ ...obj, children: [] });
          idMap[obj.orderId] = newArray[newArray.length - 1];
        } else {
          idMap[obj.orderId].children.push({ ...obj });
        }
      });
      return newArray;
    },
    /** 数据提交按钮 */
    submitForm: function () {
      this.form.roomOrderId = parseInt(this.form.roomOrderId);
      // 验证修改的数据是否规范
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.roomOrderId = parseInt(this.form.roomOrderId);
          updateOrderInfo(this.form).then((response) => {
            this.$message.success(response.msg);
            this.dialogFlag = false;
            this.title = "";
            this.clearForm();
            this.getList();
          });
        }
      });
    },
    // 提交
    // async submitForm() {
    //   this.form.roomOrderId = parseInt(this.form.roomOrderId)
    //   const data = await updateOrderInfo(this.form)
    //   console.log(this.form)
    //   this.$message.success(data.msg)
    //   this.dialogFlag = false
    //   this.clearForm()
    //   this.getList()
    // },
    // 取消提交
    cancel() {
      this.dialogFlag = false;
      // this.title = ''
      // this.clearForm()
    },
    DesCancel() {
      this.dialogFlag2 = false;
      // this.clearForm()
    },
    // 当下拉框选项变化时更新输入框的值
    updateInput() {
      const selectedRoomType = this.roomTypeOptions.find(
        (option) => option.typeName === this.form.infoName
      );
      // 如果找到了选中的房间类型对象，则更新 typeId 输入框的值
      if (selectedRoomType) {
        this.form.typeId = selectedRoomType.typeId;
        this.getroomIdOptions(this.form);
      }
    },
    // 修改按钮
    handleUpdate(row) {
      if (row.orderStatus === "已取消") {
        this.$message({
          type: "warning",
          message: "本房间已取消,无法修改",
        });
      } else if (row.orderStatus === "已退房") {
        this.$message({
          type: "warning",
          message: "本订单已完成,无法修改",
        });
      } else if (row.orderStatus === "未支付" && row.roomStatus === "可入住") {
        this.$message({
          type: "warning",
          message: "本订单已取消，无法修改！",
        });
      } else if (row.orderStatus === "已支付") {
        this.statusSel = true;
        // this.dialogFlag = true
        // this.clearForm()
        // // this.form = row
        // this.form = this.idsRow[0] || row
        this.$message({
          type: "warning",
          message: "本订单已支付,无法修改",
        });
      } else {
        this.dialogFlag = true;
        // this.clearForm()
        this.form.orderId = row.orderId;
        this.form.roomOrderId = row.roomOrderId;
        this.form.infoId = row.infoId;
        this.form.infoName = row.infoName;
        this.form.typeId = row.typeId;
        this.form.typeName = row.typeName;
        this.form.orderPrice = row.orderPrice;
        this.form.cusName = row.cusName;
        this.form.cusPhoneNum = row.cusPhoneNum;
        this.form.orderStatus = row.orderStatus;
        this.form.roomStatus = row.roomStatus;
        this.form.inTime = row.inTime;
        this.form.outTime = row.outTime;
        this.form.cusId = row.cusId;
        // this.form = row
        // console.log('row是：' + this.form)
        this.getroomIdOptions(this.form);
        // this.form = row || this.idsRow[0]
        // 根据房间入住情况控制房号修改
        if (this.form.infoId === 0) {
          this.judgeInfoId = true;
        } else {
          this.judgeInfoId = false;
        }
      }
    },
    // 清空
    clearForm() {
      for (const key in this.form) {
        if (Object.hasOwnProperty.call(this.form, key)) {
          this.form[key] = null;
        }
      }
    },
    // 树型数据
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 2 === 0) {
          return {
            rowspan: 2,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    // 下拉框查询房型
    getroomTypeOptions() {
      // 访问后端接口，查外键所有对象
      // 结果赋值this.roomTypeOptions
      listAllRoomType().then((response) => {
        this.roomTypeOptions = response.data;
      });
    },
    // 搜索
    handleQuery() {
      console.log("收到了数据");
      this.getList();
      this.queryParams.pageNum = 1;
    },
    // 重置
    resetQuery() {
      this.queryParams.infoId = null;
      this.queryParams.infoName = null;
      this.queryParams.inTime = null;
      this.queryParams.outTime = null;
      this.queryParams.cusPhoneNum = null;
      this.getList();
    },
    // 取消订单下单个房间
    handleCancel(row) {
      const { infoId, orderId, roomOrderId } = row;
      // console.log(infoId)
      // console.log(orderId)
      if (row.orderStatus === "已取消") {
        this.$message({
          type: "warning",
          message: "本房间已取消！",
        });
      } else if (row.orderStatus === "未支付" && row.roomStatus === "可入住") {
        this.$message({
          type: "warning",
          message: "本房间已取消！",
        });
      } else if (row.orderStatus === "已支付") {
        this.$message({
          type: "warning",
          message: "本订单已支付，无法取消！",
        });
      } else {
        this.$confirm("是否取消本个房间", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            cancelRoom({ infoId, orderId, roomOrderId })
              .then((response) => {
                this.$message({
                  type: "success",
                  message: response.msg,
                });
                this.getList();
              })
              .catch(() => {
                this.$message({
                  type: "error",
                  message: "操作失败",
                });
              });
            // console.log(cancelRoom({ infoId, orderId }))
            // this.$message({
            //   type: 'success',
            //   message:
            // })
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消操作",
            });
          });
      }
    },
    // 取消整个订单
    handleAllCancel() {
      const { orderId } = this.idsRow[0];
      // const { orderId } = data
      this.$confirm("是否取消订单号为" + orderId + "的整个订单", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        cancelOrder({ orderId })
          .then((response) => {
            this.$message({
              type: "success",
              message: response.msg,
            });
            this.getList();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消操作",
            });
          });
      });
    },
    // 导出按钮
    handleGenerate() {
      this.dialogFlag2 = true;
      this.clearForm();
      // this.descriptions = this.idsRow[0]
    },
    // 预定后入住
    handleCheckIn(row) {
      console.log("入住");
      if (row.orderStatus === "已取消") {
        this.$message({
          type: "warning",
          message: "本房间已取消,无法办理入住",
        });
      } else if (row.orderStatus === "已支付" && row.roomStatus === "可入住") {
        this.$message({
          type: "warning",
          message: "本订单已完成！",
        });
      } else if (row.orderStatus === "已支付" || row.roomStatus === "已入住") {
        this.$message({
          type: "warning",
          message: "本订单已入住！",
        });
      } else {
        // this.clearForm()
        const orderIdList = [];
        orderIdList.push(row.orderId);
        const jsonData = JSON.stringify(orderIdList);
        console.log(jsonData);
        judgePayDeposit(jsonData).then((response) => {
          console.log(response);
          if (response.code === 500) {
            this.dialogFlagCkeckIn = true;
            this.formTwo.typeId = row.typeId;
            this.formTwo.infoId = row.infoId;
            this.formTwo.orderId = row.orderId;
            this.formTwo.roomOrderId = row.roomOrderId;
            this.formTwo.inTime = row.inTime;
            this.formTwo.outTime = row.outTime;
            this.formTwo.roomStatus = row.roomStatus;
            console.log(this.formTwo);
            this.getroomIdOptions(this.formTwo);
          } else {
            this.$message({
              type: "warning",
              message: "请先支付押金！",
            });
          }
        });
      }
    },
    // // 押金支付状态对入住按钮的限制
    // getJudgePayCheckIn(params){
    //   const orderIdList = []
    //   orderIdList.push(params.orderId)
    //   console.log(orderIdList)
    //   const jsonData = JSON.stringify(orderIdList)
    //   console.log(jsonData)
    //   judgePayDeposit(jsonData).then((response) => {
    //     const responseStatus = response.msg
    //     console.log(response)
    //     // if (responseStatus !== '勾选列表里有订单已支付押金') {
    //     if (response.code === 500) {
    //       this.dialogFlagCkeckIn = true
    //     } else {
    //       this.$message({
    //         type: 'warning',
    //         message: '请先支付押金！'
    //       })
    //     }
    //   })
    // },

    // 下拉框查询房号
    getroomIdOptions(params) {
      // 访问后端接口，查外键所有对象
      // 结果赋值this.roomIdOptions
      checkInRoomId(params).then((response) => {
        this.roomIdOptions = response.data;
      });
      console.log(this.roomIdOptions);
    },
    // 确定入住
    async submitCheckIn() {
      console.log(this.formTwo.infoId);
      const data = await checkInRoom(this.formTwo);
      this.$message.success(data.msg);
      this.dialogFlagCkeckIn = false;
      this.clearForm();
      this.getList();
      // console.log(this.formTwo)
      console.log("提交入住房间");
    },
    // 退房
    handleCheckOut(row) {
      const { roomStatus } = this.idsRow[0] || row || {};
      const { orderStatus } = this.idsRow[0] || row || {};
      const { orderId } = this.idsRow[0] || row;
      console.log("订单状态为" + orderStatus);
      console.log({ orderId });
      if (orderStatus === "已支付" && roomStatus === "已入住") {
        this.$confirm("订单" + orderId + "确定退房？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          try {
            const method = await roomCheckOut({ orderId }); // 发起后端请求
            // console.log('输出方法：' + method)
            this.$message.success(method.msg); // 弹出成功信息
            this.getList(); // 刷新列表等操作
          } catch (error) {
            console.error("错误为:", error); // 输出错误到控制台
            // this.$message.error('请求出错，请稍后重试') // 弹出错误提示
          }
        });
      } else if (orderStatus === "已取消") {
        this.$message({
          type: "warning",
          message: "本订单已取消！",
        });
      } else if (orderStatus === "未支付" && roomStatus === "可入住") {
        this.$message({
          type: "warning",
          message: "本订单已取消！",
        });
      } else if (orderStatus === "已支付" && roomStatus === "可入住") {
        this.$message({
          type: "warning",
          message: "本订单已完成！",
        });
      } else {
        this.$message({
          type: "warning",
          message: "本订单还未支付，无法退房！",
        });
      }
    },

    // 支付宝支付
    goToPaySuccess(row) {
      const { orderStatus } = this.idsRow[0] || row || {};
      // let totalPrice = 0
      if (orderStatus === "已支付") {
        this.$message({
          type: "warning",
          message: "本订单已支付！",
        });
      } else {
        const orderInfoList = [];
        // 将多选的数据
        if (this.idsRow != null) {
          this.idsRow.forEach((idsData) => {
            const orderInfo = {
              orderId: idsData.orderId,
              orderPrice: parseInt(idsData.orderPrice, 10),
              product_code: "FAST_INSTANT_TRADE_PAY",
            };
            // 将订单信息对象添加到 orderInfoList 中
            orderInfoList.push(orderInfo);
          });
        } else {
          const orderInfo = {
            orderId: row.orderId,
            orderPrice: parseInt(row.orderPrice, 10),
            product_code: "FAST_INSTANT_TRADE_PAY",
          };
          orderInfoList.push(orderInfo);
        }

        console.log(orderInfoList);
        console.log(JSON.stringify(orderInfoList));
        // 发送Post请求到后端
        fetch("http://127.0.0.1:8081/pay/alipay", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + getToken(), // 手动添加认证 token
          },
          body: JSON.stringify(orderInfoList),
        })
          .then((response) => {
            // 检查响应的Content-Type
            if (response.headers.get("Content-Type").startsWith("text/html")) {
              // 如果是HTML，获取响应的文本内容
              return response.text();
            } else {
              throw new Error(
                "Unexpected content type: " +
                  response.headers.get("Content-Type")
              );
            }
          })
          .then((htmlContent) => {
            // 在新窗口中打开HTML内容
            const newWindow = window.open("", "_blank");
            // 将HTML内容写入新窗口的文档
            newWindow.document.write(htmlContent);
            // 关闭文档流
            newWindow.document.close();
          })
          .catch((error) => {
            console.error("Error:", error);
            // 这里可以提供用户反馈或者执行其他错误处理逻辑
          });
        this.dialogFlag3 = false;
        // // this.getList()
      }
    },

    // 现金支付
    cashPayment() {
      console.log(this.cashPayMultiple);
      // const cashPayment2 = [
      //   {
      //     orderId: this.cashPayArray.orderId,
      //     payPrice: this.cashPayArray.payPrice,
      //   },
      // ];
      const jsonData = JSON.stringify(this.cashPayMultiple);
      cashPay(jsonData).then((response) => {
        this.$message({
          type: "success",
          message: "支付成功！",
        });
        this.dialogFlag3 = false;
        this.dialogFlag4 = false;
        // 一定要再重新渲染一遍页面，不然会出现多次支付
        this.getList();
      });
    },

    // 弹出表单选择支付方式
    // 弹出表格之前要先判断支付状态是什么
    showPaymentForm() {
      console.log("showPaymentForm!");
      this.getJudgePay();
      // 因为表套表，所以要在这里先获取Id、price和status
      this.cashPayArray.orderId = this.idsRow[0].orderId;
      this.cashPayArray.payPrice = this.idsRow[0].orderPrice;
      this.cashPayArray.orderStatus = this.idsRow[0].orderStatus;
      console.log(this.cashPayArray);
      // this.getJudgePay()
    },

    // 押金支付状态、房间状态对支付房费按钮的限制
    getJudgePay() {
      const orderIdList = [];
      this.idsRow.forEach((idsData) => {
        const orderId = idsData.orderId;
        orderIdList.push(orderId);
      });
      const jsonData = JSON.stringify(orderIdList);
      judgePayDeposit(jsonData).then((response) => {
        const responseStatus = response.msg;
        // console.log(response)
        // if (responseStatus !== '勾选列表里有订单已支付押金') {
        if (response.code === 500) {
          for (let i = 0; i <= this.idsRow.length - 1; i++) {
            if (this.idsRow[i].infoId !== 0) {
              this.dialogFlag3 = true;
            } else {
              this.$message({
                type: "warning",
                message: "有订单还未办理入住，请先为其分配房间！",
              });
            }
          }
        } else {
          this.$message({
            type: "warning",
            message: "请先支付押金！",
          });
          // this.dialogFlag3 = false
        }
      });
      console.log("判断");
    },
    // 确定支付方式
    onSubmit(row) {
      console.log(this.paymentWayForm.way);
      this.cashNumForm.actuallyPay = "";
      if (this.paymentWayForm.way === "支付宝支付") {
        this.goToPaySuccess(row);
      } else {
        this.dialogFlag4 = true;
        this.totalPay = 0;
        this.cashPayMultiple = [];
        // 合并的现金支付数据获取
        console.log(this.idsRow);
        this.idsRow.forEach((idsData) => {
          const cashPayObj = {
            orderId: idsData.orderId,
            payPrice: idsData.orderPrice,
          };
          this.cashPayMultiple.push(cashPayObj);
          this.totalPay += idsData.orderPrice;
        });
        this.cashNumForm.shouldPay = this.totalPay;
        console.log(this.cashPayMultiple);
      }
    },

    // 现金支付比较后确认
    cashSubmit() {
      if (this.cashNumForm.actuallyPay < this.cashNumForm.shouldPay) {
        this.$message({
          type: "warning",
          message: "实付金额小于应付金额，请提醒客户应付金额数量",
        });
        // 一定要再重新渲染一遍页面，不然会出现多次支付
        this.getList();
      } else if (this.cashNumForm.actuallyPay === this.cashNumForm.shouldPay) {
        this.cashPayment();
      } else {
        this.cashPayment();
        const returCash =
          this.cashNumForm.actuallyPay - this.cashNumForm.shouldPay;
        this.$message({
          type: "warning",
          message: "支付成功，应找回顾客" + returCash + "元",
        });
        // 一定要再重新渲染一遍页面，不然会出现多次支付
        this.getList();
      }
    },
    // 现金支付比较后取消
    cashCancel() {
      this.dialogFlag4 = false;
    },
    depositCashCancel() {
      this.dialogFlagDPBCash = false;
    },

    // 取消选择支付方式
    paywayCancel() {
      console.log("paywayCancel!");
      this.dialogFlag3 = false;
      this.dialogFlagDeposit = false;
    },

    // 押金支付
    // 押金支付支付方式选择
    showDepositPayment() {
      // this.getJudgePayDeposit()
      const orderIdList = [];
      this.idsRow.forEach((idsData) => {
        const orderId = idsData.orderId;
        orderIdList.push(orderId);
      });
      console.log(orderIdList);
      const jsonData = JSON.stringify(orderIdList);
      console.log(jsonData);
      judgePayDeposit(jsonData).then((response) => {
        const responseStatus = response.msg;
        console.log(response);
        if (responseStatus === "勾选列表里有订单已支付押金") {
          // if (response.code === 500) {
          this.$message({
            type: "error",
            message: response.msg + "，为：" + response.data,
          });
          this.dialogFlagDeposit = false;
        } else {
          this.dialogFlagDeposit = true;
        }
      });
      console.log("支付押金");
    },

    // 押金支付确认支付方式
    onDepositSubmit() {
      console.log("押金支付确认支付方式");
      if (this.depositPaymentWayForm.way === "支付宝支付") {
        this.goToDepositPaySuccess();
      } else {
        this.clearCashPaymentByD();
        this.dialogFlagDPBCash = true;
        const orderIdList = [];
        // 获取多选的orderId
        this.idsRow.forEach((idsData) => {
          const orderId = idsData.orderId;
          orderIdList.push(orderId);
        });
        console.log(orderIdList);
        const jsonData = JSON.stringify(orderIdList);
        calculateDeposit(jsonData).then((response) => {
          console.log(response);
          this.depositCashNumForm.shouldPay = response;
        });
      }
    },

    // 刷新现金支付表单
    clearCashPaymentByD() {
      for (const key in this.depositCashNumForm) {
        if (Object.hasOwnProperty.call(this.depositCashNumForm, key)) {
          this.depositCashNumForm[key] = null;
        }
      }
    },

    // 押金现金支付
    depositPaymentByCash() {
      const orderIdList = [];
      // 获取多选的orderId
      this.idsRow.forEach((idsData) => {
        const orderId = idsData.orderId;
        orderIdList.push(orderId);
      });
      console.log(orderIdList);
      // console.log({ orderId })
      const jsonData = JSON.stringify(orderIdList);
      console.log(jsonData);
      payDepositByCash(jsonData).then(() => {
        this.$message({
          type: "success",
          message: "现金支付成功!",
        });
        this.getList();
      });

      this.dialogFlagDeposit = false;
      this.dialogFlagDPBCash = false;
    },

    // 现金支付时的比较
    depositCashSubmit() {
      if (
        this.depositCashNumForm.actuallyPay < this.depositCashNumForm.shouldPay
      ) {
        this.$message({
          type: "warning",
          message: "实付金额小于应付金额，请提醒客户应付金额数量",
        });
        this.getList();
      } else if (
        this.depositCashNumForm.actuallyPay ===
        this.depositCashNumForm.shouldPay
      ) {
        this.depositPaymentByCash();
      } else {
        this.depositPaymentByCash();
        const returCash =
          this.depositCashNumForm.actuallyPay -
          this.depositCashNumForm.shouldPay;
        this.$message({
          type: "warning",
          message: "支付成功，应找回顾客" + returCash + "元",
        });
        this.getList();
      }
    },
    // 押金支付宝支付
    goToDepositPaySuccess(row) {
      const list = [];
      const orderIdList = [];
      this.idsRow.forEach((idsData) => {
        // const orderInfo = {
        const orderId = idsData.orderId;
        // 将订单id对象添加到 orderInfoList 中
        orderIdList.push(orderId);
      });
      // console.log(orderInfo)
      console.log(orderIdList);
      console.log(JSON.stringify(orderIdList));
      // 发送Post请求到后端
      fetch("http://127.0.0.1:8081/pay/payDepositByAli", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + getToken(), // 手动添加认证 token
        },
        // body: JSON.stringify(orderId)
        body: JSON.stringify(orderIdList),
      })
        .then((response) => {
          // 检查响应的Content-Type
          if (response.headers.get("Content-Type").startsWith("text/html")) {
            // 如果是HTML，获取响应的文本内容
            return response.text();
          } else {
            throw new Error(
              "Unexpected content type: " + response.headers.get("Content-Type")
            );
          }
        })
        .then((htmlContent) => {
          // 在新窗口中打开HTML内容
          const newWindow = window.open("", "_blank");
          // 将HTML内容写入新窗口的文档
          newWindow.document.write(htmlContent);
          // 关闭文档流
          newWindow.document.close();
        })
        .catch((error) => {
          console.error("Error:", error);
          // 这里可以提供用户反馈或者执行其他错误处理逻辑
        });
      this.dialogFlagDeposit = false;
    },

    // 设置退房时间设置
    outTimeDisabledDate(time) {
      // 获取入住时间
      const inTime = new Date(this.form.inTime);
      // 如果入住时间为空，返回 false，即不禁用任何日期
      if (!inTime) return false;
      // 禁用入住时间之前的日期
      return time.getTime() < inTime.getTime();
    },

    // 处理分页
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
  },
};
</script>
<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 30%;
}
</style>
